package models

import (
	"gorm.io/gorm"
	"time"
)

// Routes 路由表结构体与数据库绑定
type Routes struct {
	ID            uint64    `gorm:"column:id;primary_key;auto_increment" json:"id" form:"id"`
	RouteName     string    `gorm:"column:route_name;type:varchar(255);not_null" json:"route_name" form:"route_name"`
	RoutePath     string    `gorm:"column:route_path;type:varchar(255);uniqueIndex;not_null" json:"route_path" form:"route_path"`
	ComponentName string    `gorm:"column:component_name;type:varchar(255);uniqueIndex;not_null" json:"component_name" form:"component_name"`
	ParentID      *uint64   `gorm:"column:parent_id;type:bigint;default:null" json:"parent_id" form:"parent_id"`
	Description   string    `gorm:"column:description;type:text" json:"description" form:"description"`
	CreatedAt     time.Time `gorm:"column:created_at;default:CURRENT_TIMESTAMP" json:"created_at" form:"created_at"`
	UpdatedAt     time.Time `gorm:"column:updated_at;default:CURRENT_TIMESTAMP;update_default:CURRENT_TIMESTAMP" json:"updated_at" form:"updated_at"`
}

// TableName 指定结构体对应的数据库表名
func (Routes) TableName() string {
	return "routes"
}

// RouteTree 树形路由结构体（用于返回树形结构）
type RouteTree struct {
	ID            uint64      `json:"id"`
	RouteName     string      `json:"route_name"`
	RoutePath     string      `json:"route_path"`
	ComponentName string      `json:"component_name"`
	Description   string      `json:"description"`
	Children      []RouteTree `json:"children"` // 子路由列表
}

// GetSubRoutesByRouteIDs
//
// 描述信息：根据路由ID列表获取所有子目录的路由信息，并以树形结构返回
//
// Param：
//
//	db ：mysql链接
//	routeIDs ：路由ID列表
//
// Return：
//
//	[]RouteTree ：查询到的子目录路由列表（树形结构）
//	error ：错误信息
func GetSubRoutesByRouteIDs(db *gorm.DB, routeIDs []uint64) ([]RouteTree, error) {
	if len(routeIDs) == 0 {
		return []RouteTree{}, nil
	}

	var allRoutes []Routes
	result := db.Find(&allRoutes)
	if result.Error != nil {
		return nil, result.Error
	}

	routeMap := make(map[uint64]Routes)
	for _, route := range allRoutes {
		routeMap[route.ID] = route
	}

	var tree []RouteTree
	for _, id := range routeIDs {
		tree = append(tree, buildTreeFromID(routeMap, id))
	}

	return tree, nil
}

func buildTreeFromID(routeMap map[uint64]Routes, id uint64) RouteTree {
	route, exists := routeMap[id]
	if !exists {
		return RouteTree{}
	}

	var children []RouteTree
	childIDs := getChildIDs(routeMap, id)
	for _, childID := range childIDs {
		children = append(children, buildTreeFromID(routeMap, childID))
	}

	return RouteTree{
		ID:            id,
		RouteName:     route.RouteName,
		RoutePath:     route.RoutePath,
		ComponentName: route.ComponentName,
		Description:   route.Description,
		Children:      children,
	}
}

func getChildIDs(routeMap map[uint64]Routes, parentID uint64) []uint64 {
	var childIDs []uint64
	for id, route := range routeMap {
		if route.ParentID != nil && *route.ParentID == parentID {
			childIDs = append(childIDs, id)
		}
	}
	return childIDs
}
